package com.teach.config;

import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;



/**
 * <pre>
 * TODO : Mybatis-plus配置
 * ClassName : sys.config.MybatisPlusConfig
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 15111047708
 * Date : 2020-09-13 11:36
 * Version : V1.0
 * Copyright 2020 jlzhou.top Inc. All rights reserved. 
 * Warning: this content is only for internal circulation of the company. It is forbidden to divulge it or use it for other commercial purposes</pre>
 */
@Configuration
@MapperScan("com.teach.mapper")
@AutoConfigureAfter(Config.class)
public class MybatisPlusConfig {
	
	private static Logger log = LoggerFactory.getLogger(MybatisPlusConfig.class);
    
	@Autowired
	private Config config;
	
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
    	MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    	
    	PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
    	paginationInnerInterceptor.setOverflow(true);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInnerInterceptor.setMaxLimit(500L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        log.info("添加了MybatisPlus的分页拦截器");
        
        BlockAttackInnerInterceptor blockAttackInnerInterceptor = new BlockAttackInnerInterceptor();
        interceptor.addInnerInterceptor(blockAttackInnerInterceptor);
        log.info("添加了MybatisPlus的防止全表更新与删除拦截器");
        
        return interceptor;
    }
    

	
	@Bean
	@Primary
	public Sequence sequence() {
		return new Sequence(config.workerId, config.dataCenterId) {
			@Override
			public synchronized long nextId() {
				long id = super.nextId();
				log.debug("分布式id生成器workerId：{}，dataCenterId：{}，生成id:{}",config.workerId, config.dataCenterId,id);
				return id;
			}
		};
	}
	
    @Bean
    @Primary
    public IdentifierGenerator identifierGenerator (Sequence sequence) {
    	return new DefaultIdentifierGenerator(sequence);
    }
    
}
